package com.lwq.service.impl;

import com.lwq.entity.Order;
import com.lwq.entity.Product;
import com.lwq.feign.ProductFeign;
import com.lwq.mapper.OrderMapper;
import com.lwq.rabbitmqutil.RabbitMqConstant;
import com.lwq.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwq.util.JacksonUtil;

import com.lwq.util.Result;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author lwq
 *
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductFeign productFeign;

    @Override
    public int insert(Order order) {

        // 获取商品主键
        Integer productId = order.getProductId();

        // 调用商品微服务的的 `按主键查询商品信息` 方法
        Result result = productFeign.selectById(productId);
        if (result.getCode() <= 0) {
            throw new RuntimeException("商品信息查询失败");
        }

        // 将结果中的Product实体数据解析出来
        Product product = JacksonUtil.parseData(result.getData(), Product.class);

        // 填充实体类
        order.setProductName(product.getProductName());

        // 调用添加订单的数据方法
        int insertResult = orderMapper.insert(order);
        if (insertResult < 0) {
            throw new RuntimeException("订单添加失败");
        }

        // 添加成功后，进行扣减库存
        Result reduceResult = productFeign.reduceInventory(productId, order.getNumber());
        if (reduceResult.getCode() < 0) {
            throw new RuntimeException("扣减库存失败");
        }

        System.out.println(sendMsg("已完成购买商品"));

        // 添加一条订单记录
        return insertResult;
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @SneakyThrows
    public String sendMsg(String msg) {

        // 准备消息数据
        Map<String, Object> messageMap = new HashMap<>(2);
        messageMap.put("id", UUID.randomUUID().toString());
        messageMap.put("msg", msg);

        // 发送消息
        rabbitTemplate.convertAndSend(
                RabbitMqConstant.EXCHANGE,
                RabbitMqConstant.ROUTING_KEY,
                messageMap);

        return "消息发送成功";
    }
}
